#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
名称解析模块，提供查找类全限定名的功能

开发者: 
职责: 实现类名称解析功能，根据简单类名查找其全限定名
"""

import os
from typing import List, Optional
from functools import lru_cache

from parser.refactor.data_structures import ClassInfo, PackageInfo

@lru_cache(maxsize=1000)
def resolve_full_qualified_name(
    simple_name: str,
    source_class: ClassInfo,
    packages: List[PackageInfo],
    classes: List[ClassInfo]
) -> Optional[str]:
    """
    查找类的全限定名

    Args:
        simple_name: 简单类名
        packages: 已知包信息列表
        classes: 已知类信息列表
        source_class: 当前源类信息

    Returns:
        找到的全限定名，未找到返回None
    """
    # # 步骤1: 检查已知类列表
    # for cls in classes:
    #     if cls.name == simple_name:
    #         return cls.full_name

    # 步骤2: 检查导入语句
    imports = source_class.imports
    for import_stmt in imports:
        # 检查直接导入 (如 import com.example.MyClass)
        if import_stmt.endswith("." + simple_name):
            return import_stmt
    
    # 步骤3: 检查通配符导入 (import prefix.*)
    for import_stmt in imports:
        if import_stmt.endswith(".*"):
            prefix = import_stmt[:-2]  # 去除 .*
            
            # 3.1 检查是否存在该包
            for package in packages:
                if package.name == prefix:
                    # 在包路径下查找类文件
                    for cls in classes:
                        if cls.package == prefix and cls.name == simple_name:
                            return f"{prefix}.{simple_name}"
            
            # 3.2 检查前缀是否匹配某个类，查找其内部类
            for cls in classes:
                if cls.full_name == prefix:
                    inner_class_fqn = f"{prefix}.{simple_name}"
                    if inner_class_fqn in cls.inner_classes:
                        return inner_class_fqn

    # 步骤4: 检查当前源类所在包
    if source_class and source_class.package:
        # 在同包下查找
        for cls in classes:
            if cls.package == source_class.package and cls.name == simple_name:
                return cls.full_name
        
        # 步骤5: 检查是否为当前类的内部类
        inner_class_fqn = f"{source_class.full_name}.{simple_name}"
        if inner_class_fqn in source_class.inner_classes:
            return inner_class_fqn

    # 未找到匹配的全限定名
    return None 